package com.xzuf.core.ui;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xzuf.core.vo.PluginTreeVO;
import com.xzuf.core.vo.PluginVO;
import com.xzuf.pub.GlobalValue;
import com.xzuf.xml.XmlUtils;

/**
 * @author xzgf
 * @since 2008-7-12
 * @version 1.0
 */
public class ActionManager {

	private static final Log logger = LogFactory.getLog(ActionManager.class);
	
	private static ImageIcon icon_refreshPlugin;
	
	private static ImageIcon icon_help;
	
	private static ImageIcon icon_exit;
	
	private static ImageIcon icon_tray;
	
	private static UIAction pluginRefreshAction;
	
	private static UIAction aboutAction;
	
	private static UIAction exitAction;
	
	private static UIAction trayAction;
	
	private static UIAction[] managerActions;
	
	private static UIAction[] helpAction;
	
	private static TrayIcon trayIcon = null;
	
	private static SystemTray tray = null;
	
	private static List<PluginVO> pluginList = new ArrayList<PluginVO>();
	
	static {
		icon_refreshPlugin = new ImageIcon(ActionManager.class.getResource("images/refresh.gif"));
		icon_help = new ImageIcon(ActionManager.class.getResource("images/help.png"));
		icon_exit = new ImageIcon(ActionManager.class.getResource("images/exit.png"));
		icon_tray = new ImageIcon(ActionManager.class.getResource("images/xml.png"));
		pluginRefreshAction = new UIAction("刷新插件",icon_refreshPlugin) {
			@Override
			public void actionPerformed(ActionEvent e) {
				refreshPluginTree();
			}
		};
		aboutAction = new UIAction("关于",icon_help) {
			@Override
			public void actionPerformed(ActionEvent e) {
				 About dlg = new About();
			        dlg.setLocationRelativeTo(null);
			        dlg.setModal(true);
			        dlg.setResizable(false);
			        dlg.setVisible(true);
			        dlg.dispose();
			}
		};
		exitAction = new UIAction("退出",icon_exit) {
			@Override
			public void actionPerformed(ActionEvent e) {
				logger.debug("System will be shut down...");
				System.exit(0);
			}
		};
		trayAction = new UIAction("最小化到任务栏",icon_tray) {
			@Override
			public void actionPerformed(ActionEvent e) {
				onTray();
			}
		};
	}
	
	private static void onTray() {
		
		if(SystemTray.isSupported()) {
			tray = SystemTray.getSystemTray();
			Image image = Toolkit.getDefaultToolkit().getImage(ActionManager.class.getResource("images/xml.png"));
			ActionListener listener = new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					if(e.getSource() instanceof MenuItem ) {
						MenuItem menu = (MenuItem)e.getSource();
						if(menu.getLabel().equals("显示")) {
							tray.remove(trayIcon);
							GlobalValue.mainFrame.setVisible(true);
						} else if(menu.getLabel().equals("退出")) {
							System.exit(0);
						}
					}
				}
			};
			
			MouseListener mouseListener = new MouseListener() {
				@Override
				public void mouseClicked(MouseEvent e) {
					if(e.getClickCount() == 2) {
						tray.remove(trayIcon);
						GlobalValue.mainFrame.setVisible(true);
					}
				}
				@Override
				public void mouseEntered(MouseEvent e) {
				}
				@Override
				public void mouseExited(MouseEvent e) {
				}
				@Override
				public void mousePressed(MouseEvent e) {
				}
				@Override
				public void mouseReleased(MouseEvent e) {
				}
			};
			
			PopupMenu popup = new PopupMenu();
			MenuItem menuItem0 = new MenuItem("显示");
			MenuItem menuItem1 = new MenuItem("退出");
			
			menuItem0.addActionListener(listener);
			menuItem1.addActionListener(listener);
			
			popup.add(menuItem0);
			popup.add(menuItem1);
			trayIcon = new TrayIcon(image,"可扩展应用平台",popup);
			trayIcon.addActionListener(listener);
			trayIcon.addMouseListener(mouseListener);
			try {
				tray.add(trayIcon);
			} catch (AWTException e1) {
				e1.printStackTrace();
			}
			
			GlobalValue.mainFrame.setVisible(false);
		}
	}
	
	public static List<PluginVO> refreshPluginTree() {
		
		String pluginPath = GlobalValue.PLUGIN_DIR;
		try {
			File pluginDir = new File(pluginPath);
			File[] files = pluginDir.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					if(name.endsWith(".xml")) {
						return true;
					}
					return false;
				}
			});
			if(files != null) {
				logger.info("Find [" + files.length + "] Plugings..");
				PluginVO pvo = null;
				PluginTreeVO vo = null;
				for(File file : files) {
					logger.info("Loading Plugin in [" + file.getAbsolutePath() + "]");
					pvo = XmlUtils.getXmlUtils().readPluginXml(file.getAbsolutePath());
					vo = new PluginTreeVO();
					vo.setClassName(pvo.getExtension().get(0).getRuntime().getRunclass());
					vo.setPluginCode(pvo.getPlugincode());
					vo.setPluginName(pvo.getPluginname());
					pluginList.add(pvo);
				}
//				buildPluginTree(pluginList);
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		return pluginList;
	}
	
	public static void buildPluginTree(List<PluginTreeVO> treeVOList) {
		if(treeVOList == null) {
			logger.error("未发现任何插件配置..");
			return;
		}
		JTree pluginTree = GlobalValue.pluginTree;
		DefaultTreeModel treeModel = (DefaultTreeModel)pluginTree.getModel();
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)treeModel.getRoot();
		root.removeAllChildren();
		DefaultMutableTreeNode[] treeNodes = new DefaultMutableTreeNode[treeVOList.size()];
		for(int i=0;i<treeNodes.length;i++) {
			treeNodes[i] = new DefaultMutableTreeNode();
			treeNodes[i].setUserObject(treeVOList.get(i));
			root.add(treeNodes[i]);
		}
		pluginTree.updateUI();
	}
	
	public static UIAction[] getManagerActions() {
		managerActions = new UIAction[] {
			pluginRefreshAction,exitAction,trayAction
		};
		return managerActions;
	}
	
	public static UIAction[] getHelpActions() {
		helpAction = new UIAction[] {
				aboutAction
		};
		return helpAction;
	}
}
